<?php

namespace App\Services;

use App\Models\Cdr;
use App\Models\CdrAddtion;
use App\Models\Phone;
use App\Models\PhoneRecord;
use App\Models\PhoneSetting;
use App\Models\RecordFileInfo;
use App\Models\Task;
use Carbon\Carbon;
use Chumper\Zipper\Zipper;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class SipService
{
    protected $beforeTime;

    public function __construct()
    {
        $this->beforeTime = env('SYNC_SIP',5);

    }

    //获取前10分钟的通话录音记录
    public function getBeforePhoneRecord(){
        //获取电话配置类型为SIP的配置ID
        $phone_settings = PhoneSetting::where([
            ['type','=','sip'],
        ])->pluck('id')->toArray();

        // 获取筛选的日期
        $date =  Carbon::now()->subMinutes($this->beforeTime+10)->toDateTimeString();

        //取出SIP得所有电话号码
        $phones = Phone::whereIn('phone_setting_id',$phone_settings)->pluck('phone_number')->toArray();

        //筛选出sip数据库的cdr表中符合条件的数据
        $phone_records = CdrAddtion::where([
            ['start_stamp','>=',$date],
        ])->whereIn('caller_id_number',$phones)->get()->toArray();

        //更新本地电话记录
        if($phone_records){

            foreach ($phone_records as $v){
                $time = strtotime($v['start_stamp'])-60*$this->beforeTime;
                $time = date("Y-m-d H:i:s",$time);

                $phone_record = PhoneRecord::where([
                    ['user_phone','=',$v['caller_id_number']],
                    ['fs_user_phone','=',$v['destination_number']],
                    ['created_at','<',$v['start_stamp']],
                    ['created_at','>',$time]
                ])->orderBy('created_at','DESC')->first();

                if($phone_record){
                    //查找是否有录音文件
//                    $file_name = date('Y-m-d-H-i-s',strtotime($v['start_stamp']))."-{$v['destination_number']}_172.31.194.139_{$v['caller_id_number']}.zip";
                    $file_name_a = date('Y-m-d-H-i-s',strtotime($v['start_stamp']));
                    $file_name_b = $v['destination_number'];
                    $file_name_c = '172.31.194.139';
                    $file_name_d = $v['caller_id_number'];
                    $file_name = $file_name_a.'_'.$file_name_b.'_'.$file_name_c.'_'.$file_name_d.'.zip';
                    $phone_luyin = RecordFileInfo::where([
                        'file_name' => $file_name  //'2019-02-18-18-30-39_928618826581103_172.31.194.139_d001s002.zip'
                    ])->first();
                    Log::info('查找录音ming',['a'=>$file_name_a,'b'=>$file_name_b,'c'=>$file_name_c,'d'=>$file_name_d,'data'=>$file_name,'msg'=>$phone_luyin]);
                    $recording_url = '';
                    $voice_url = '';
                    //录音文件存在则去下载
//                    if($phone_luyin){
//                        $recording_url = sipRecrodUrl($phone_luyin->oss_path); //http://www.tdcall.net/2019-02-19/2019-02-19-21-38-45_928618911392274_172.31.194.139_d001s002.zip
//                        $voice_url = $this->upload($recording_url,$phone_luyin->file_name); //本地的录音地址
//                        Log::info('本地录音地址',['msg'=>$voice_url]);
//                    }
                    //存在则更新
                    $phone_record->update([
                        'call_status' => $v['status']==1?'completed':'cancel',
                        'recording_url' => $recording_url,
                        'recording_time' => $v['billsec'],
                        'updated_at' => $v['end_stamp'],
                        'voice_url' => $voice_url,
                    ]);
                   //通话状态为0的时候才去修改
                    if($phone_record->task_id){
                        $res = DB::table('fs_user_tasks')->where([
                            ['task_id','=',$phone_record->task_id],
                            ['fs_user_id','=',$phone_record->fs_user_id],
                        ])->first();
                        if($res->status===0){
                            DB::table('fs_user_tasks')->where([
                                ['task_id','=',$phone_record->task_id],
                                ['fs_user_id','=',$phone_record->fs_user_id],
                            ])->update(['status'=>1,'call_time'=>Carbon::now()]);
                        }
                    }
                }
            }
       }
    }

    /**
     * 解压文件放到本地返回绝对地址
     * @param $httpUrl sip的录音地址 如http://www.tdcall.net/2019-02-18/2019-02-18-18-30-39_928618826581103_172.31.194.139_d001s002.zip
     * @param $fileName 文件名称   如2019-02-18-18-30-39_928618826581103_172.31.194.139_d001s002.zip
     */
    public function upload($httpUrl ='',$fileName){
        if($httpUrl){
            $httpUrl = 'http://www.tdcall.net/'.$httpUrl;
            $local_url = voiceUploadA($httpUrl,$fileName);
            $path = public_path($local_url);  //"/home/vagrant/Code/dianyun2/public/uploads/voice/201902/19/xxxx.zip"
            if($path){
                $zip = new Zipper();
                $dir = "/uploads/voice/" . date("Ym/d", time()).'/';

                $rr = $zip->make($path)->extractTo(public_path($dir));

                return config('app.url').$dir. str_replace('zip','wav',$fileName);
            }
        }

    }

    /**
     * 删除文件
     * @param $fileName 要删除的录音ZIP文件名
     */
    public function deleteZip($fileName){
        $dir = "uploads/voice/" . date("Ym/d", time()).'/';
        $delete_file = $dir.$fileName;
        Log::info('deleteZip',[$delete_file]);
        Storage::disk('public')->delete($delete_file);
    }

    /**
     * 修改task表状态字段
     * @param $validatedData
     * $validatedData['id']   fs_user_id
     * $validatedData['task_id']  task_id
     * 0 完成 1已完成 3逾期未完成  4逾期完成
     */
    public function taskStatus($validatedData){
        if(empty($validatedData['task_id'])){
            return;
        }
        $task = Task::find($validatedData['task_id']);
        if($task){
            //打通电话人数
            $call_count = $task->fsUserTask->where('status',1)->count();
            //任务会员人数
            $count = $task->count;
            //（完成度100%）任务的人数等于 任务会员表status为1 的数量
            if($call_count == $count){
                //最后一通电话的通话时间
                $call_end_time = $task->fsUserTask->sortByDesc('call_time')->first()->call_time;
                //任务结束时间
                $task_end_time = $task->end_time;

                if($call_end_time <= $task_end_time ){
                    //完成任务 1
                    DB::table('tasks')->where('id',$validatedData['task_id'])->update(['status' => 1]);
                }else{
                    //逾期完成任务 4
                    DB::table('tasks')->where('id',$validatedData['task_id'])->update(['status' => 4]);
                }
            }elseif ($task->end_time < date('Y-m-d H:i:s',time()) && $task->status === 0){
                //当前时间大于任务结束时间
                //逾期未完成 3
                DB::table('tasks')->where('id',$validatedData['task_id'])->update(['status' => 3]);
            }
        }
    }

    /**
     * 查询CDR的录音
     * @param $crd_record  要查找的录音文件名
     *
     */
    public function searchCdrRecord($file_name){
        $phone_luyin = RecordFileInfo::where([
            'file_name' => $file_name  //'2019-02-18-18-30-39_928618826581103_172.31.194.139_d001s002.zip'
        ])->first();
        if($phone_luyin){
            return $phone_luyin;
        }
        $phone_luyin = RecordFileInfo::where([
            'file_name' => addSecond($file_name)  //'2019-02-18-18-30-39_928618826581103_172.31.194.139_d001s002.zip'
        ])->first();
        if($phone_luyin){
            return $phone_luyin;
        }
        $phone_luyin = RecordFileInfo::where([
            'file_name' => subSecond($file_name)  //'2019-02-18-18-30-39_928618826581103_172.31.194.139_d001s002.zip'
        ])->first();
        if($phone_luyin){
            return $phone_luyin;
        }
    }

    /**
     * CDR录音文件名称
     * @param $crd_record  crd的通话记录
     * @return $file_name  要查找的文件名称
     */
    public function cdrFileName($crd_record){
        //cdr录音表中的条件字段
        $file_name_a = date('Y-m-d-H-i-s',strtotime($crd_record['start_stamp']));
        $file_name_b = $crd_record['destination_number'];
        $file_name_c = '172.31.194.139';
        $file_name_d = $crd_record['caller_id_number'];
        $file_name = $file_name_a.'_'.$file_name_b.'_'.$file_name_c.'_'.$file_name_d.'.zip';
        Log::info('查询录音文件',['b'=>$file_name]);
        return $file_name;
    }

}